﻿using AutoMapper;
using KC.Framework.Base;
using KC.Model.Account;
using KC.Service.Account.AutoMapper.Converter;
using KC.DTO.Account;
using KC.DTO.Core;
using System.Collections.Generic;
using System.Linq;

namespace KC.Service.Account.AutoMapper.Profile
{
    public class PermissionMapperProfile : global::AutoMapper.Profile
    {
        public PermissionMapperProfile()
        {
            CreateMap<Permission, PermissionDTO>()
                .ConvertUsing<PermissionConverter>();
            CreateMap<PermissionDTO, Permission>()
                .ConvertUsing<PermissionDTOConverter>(); ;

            CreateMap<Permission, PermissionSimpleDTO>()
                .ForMember(target => target.id, config => config.MapFrom(src => src.Id))
                .ForMember(target => target.text, config => config.MapFrom(src => src.Name))
                //.ForMember(target => target.ParentName,
                //    config => config.MapFrom(src => src.ParentNode != null ? src.ParentNode.Name : string.Empty))
                .ForMember(target => target.children, config => config.MapFrom(src => src.ChildNodes))
                .ForMember(target => target.@checked, config => config.Ignore());
            
            CreateMap<PermissionSimpleDTO, TreeSimpleDTO>()
                .ForMember(target => target.id, config => config.MapFrom(src => src.id))
                .ForMember(target => target.text, config => config.MapFrom(src => src.text))
                .ForMember(target => target.@checked, config => config.MapFrom(src => src.@checked))
                .ForMember(target => target.children, config => config.MapFrom(src => src.children));

            CreateMap<Role, RoleSimpleDTO>()
                .ForMember(target => target.RoleId, config => config.MapFrom(src => src.Id))
                .ForMember(target => target.RoleName, config => config.MapFrom(src => src.Name))
                .ForMember(target => target.DisplayName, config => config.MapFrom(src => src.DisplayName))
                .ForMember(target => target.UserIds,
                    config => config.MapFrom(src => src.RoleUsers.Select(m => m.UserId).ToList()))
                .ForMember(target => target.MenuNodes,
                    config =>
                        config.MapFrom(
                            src => Mapper.Map<List<MenuNodeSimpleDTO>>(src.RoleMenuNodes.Select(m => m.MenuNode).Where(m => !m.IsDeleted))))
                .ForMember(target => target.Permissions,
                    config =>
                        config.MapFrom(
                            src => Mapper.Map<List<PermissionSimpleDTO>>(src.RolePermissions.Select(m => m.Permission).Where(m => !m.IsDeleted))))
                .ForMember(target => target.@checked, config => config.Ignore());
        }
    }
}
